﻿package tk.mystudio.web.security;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Service;

import tk.mystudio.permission.bean.Account;
import tk.mystudio.permission.exception.AccountNotExistException;
import tk.mystudio.permission.service.AccountService;


@Service("loginManager")
public class AuthManager extends SimpleUrlAuthenticationSuccessHandler
		implements UserDetailsService {

	private final Logger logger = LoggerFactory.getLogger(AuthManager.class);

	@Resource
	private AccountService accountService;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication authentication)
			throws IOException, ServletException {
		WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();
		Date now = new Date();
		Account account = (Account) authentication.getPrincipal();
//		Account account = accountService.getAccountByName(authentication
//				.getName());
		// 这里实际上设置的是本次登录的IP和时间
		account.setLastLoginIp(details.getRemoteAddress());
		account.setLastLoginTime(now);

		accountService.updateAccount(account);

		super.onAuthenticationSuccess(request, response, authentication);
	}

	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		Account account;
		try {
			account = accountService.getAccountByName(username);
			return account;
		} catch (AccountNotExistException e) {
			logger.error(e.getMessage());
			throw new UsernameNotFoundException(e.getMessage());
		}
	}

	public void setAccountService(AccountService accountService) {
		this.accountService = accountService;
	}

}
